package my.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.sjcx.common.HtmlUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import my.common.BaseController;
import my.common.WriteToFiles;
import my.service.StorageService;

@Controller
public class DemoController extends BaseController{
	static Log log = LogFactory.getLog(DemoController.class);
	private static HtmlUtil htmlRegexp;
	private static String[] netUrl = {
			"http://www.x23us.com/html/0/344/"
	};
	static Document doc = null;
	/**
	 * 获取章节
	 */
	public static String getContentUrl(int num){
		doc = null;
		HashMap<Object, Object> map = new HashMap<Object, Object>();
		try {
			doc = Jsoup.connect(netUrl[0]).get();
			
			Element content = doc.getElementById("at");
			Elements links = content.getElementsByTag("a");
			int i = 0;
			for (Element link : links) {
			  String linkHref = link.attr("href");
			  String linkText = link.text();
			  i++;
//			  System.out.println(netUrl[0]+linkHref + "--" +linkText);
			  map.put(i, netUrl[0]+linkHref);
			  //getContent(); 
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map.get(num).toString();
	}
	
	public static String getContent(int num){
		doc = null;
		String con = null;
		try {
			doc = Jsoup.connect(getContentUrl( num )).get();
			Element content = doc.getElementById("contents");
			con = content.text();
			con = con.replaceAll("２３Ｕｓ．ｃｏｍ", "");
			con = con.replaceAll("(看小说到顶点小说网www.x23us.com)", "");
			con = con.replaceAll(" ", "<br>\n");
//			System.out.println( con );
			
			log.info(con);
			
//			try {
//				new WriteToFiles().WriteToFile2("E:/proxy.txt" , con);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			File img = new File("‪E:/proxy.txt");
//	    	String path = StorageService.FILES.save(img);
//	    	
//	    	System.out.println( path );
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return con;
	}
	
	@RequestMapping(value="/pages/{pageNum}" , method=RequestMethod.GET)
	public String returnGetTest(ModelMap model , @PathVariable("pageNum") String content){
		
		model.addAttribute("content", getContent( Integer.parseInt(content) ));
		//toWrite(name);
		return "name";
	}
	
	public static void main(String[] args) {
		getContent(100);
	}
}
